package com.laike.pay.activity;

import android.os.Handler;
import android.util.Log;

import com.laike.pay.bean.PayOrder;
import com.laike.pay.http.BaseCallback;
import com.laike.pay.http.HttpRetrofit;
import com.laike.pay.http.ParamsUtils;
import com.laike.pay.http.Result;
import com.laike.pay.http.api.ApiName;
import com.laike.pay.http.api.SerivceApi;
import com.laike.pay.utils.ProgressDialogUtils;
import com.laike.pay.utils.SharedPreferencesUtils;
import com.laike.pay.utils.ToastUtils;

import org.json.JSONObject;

import java.util.Map;

import retrofit2.Call;
import retrofit2.Response;


public class BrushCard2Activity extends BrushCardActivity {
    private static final String PAY_TYPE = "22";
    private PayOrder order = null;

    @Override
    public void getOrderId() {
        //刷卡
        if (coollectMoney()) {
            String sum = value.getText().toString();//金额
            ProgressDialogUtils.showProgress(this, "正在下单...");
            HttpRetrofit.getInstance().getInterfaceApi(SerivceApi.class).getOrderId(appidStr, ApiName.GET_ORDER_ID, terminalNumber,
                    ParamsUtils.getOrderId(sum, PAY_TYPE), sum, PAY_TYPE).enqueue(new BaseCallback<Result<PayOrder>>() {
                @Override
                public void onResponse(Call<Result<PayOrder>> call, Response<Result<PayOrder>> response) {
                    ProgressDialogUtils.dismissProgress();
                    if (response.code() == 200) {
                        if (response.body().getStatus().equals("1")) {
                            order = response.body().getData();
                            switch (typeValue) {
                                case 1:
                                    brushCard(order);
                                    break;
                                case 3:
                                    brushCardNow(order);
                                    break;
                            }
                        } else {
                            ToastUtils.showToast(BrushCard2Activity.this, response.body().getInfo() + "");
                        }
                    }
                }

                @Override
                public void onFailure(Call<Result<PayOrder>> call, Throwable t) {
                    ProgressDialogUtils.dismissProgress();
                    Log.v("---onFailure--", "error message:" + t.getMessage());
                }
            });
        }
    }
    private void showError() {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToast(BrushCard2Activity.this, "刷卡启动失败，请退出系统重试");
            }
        });
    }

    /**
     * 百富刷卡支付
     *
     * @param order
     */
    private void brushCard(final PayOrder order) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    JSONObject json = new JSONObject();
                    json.put("transType", "SALE");
                    json.put("transAmount", getAmount(order.getTotal_amount()));
                    json.put("appId", SharedPreferencesUtils.getAppid());
                    final String result = payHelper.doTrans(json.toString());
                    Log.i("TAG","----result----"+result);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            doSuccess(result);
                        }
                    });
                } catch (Exception e) {
                    showError();
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 百富实时消费
     *
     * @param order
     */
    private void brushCardNow(final PayOrder order) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    JSONObject json = new JSONObject();
                    json.put("transType", "SALE_NOW");
                    json.put("transAmount", getAmount(order.getTotal_amount()));
                    json.put("appId", SharedPreferencesUtils.getAppid());
                    final String result = payHelper.doTrans(json.toString());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            doSuccess(result);
                        }
                    });
                } catch (Exception e) {
                    showError();
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //处理支付结果
    private void doSuccess(String result) {
        try {
            String voucherNo = "";
            JSONObject json = new JSONObject(result);
            voucherNo = json.getString("voucherNo");//凭证号
            addOrder(voucherNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //将交易金额统一处理成12位，不足12位的在前面补0
    private String getAmount(String amount) {
        int price = Integer.parseInt(amount.replace(".", ""));
        String temp = price + "";
        while (temp.length() < 12) {
            temp = "0" + temp;
        }
        return temp;
    }

    private void addOrder(final String traceNo) {
        ProgressDialogUtils.showProgress(BrushCard2Activity.this, "订单处理中");
        HttpRetrofit.getInstance().getInterfaceApi(SerivceApi.class).addOrder(order.getRqcode_url(),
                order.getOut_trade_no(), traceNo, order.getTotal_amount(), "shengpay.bankcard")
                .enqueue(new BaseCallback<Result<Map<String, String>>>() {
            @Override
            public void onResponse(Call<Result<Map<String, String>>> call, Response<Result<Map<String, String>>> response) {
                ProgressDialogUtils.dismissProgress();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showToast(BrushCard2Activity.this, "订单成功传入后台");
                        reset();
                    }
                });
            }

            @Override
            public void onFailure(Call<Result<Map<String, String>>> call, Throwable t) {
                ProgressDialogUtils.dismissProgress();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        addOrder(traceNo);
                    }
                }, 10000);
                Log.v("onFailure", "error message :" + t.getMessage());
            }
        });
    }
}
